﻿using System;
using System.Linq;
using System.Web.Mvc;
using MiddleMVCTask.BL.ViewModels;
using MiddleMVCTask.BL.Interfaces;

namespace MiddleMvcTask.Controllers
{
    public class AccountController : Controller
    {
        /// <summary>
        /// Represent a instance of business logic layer
        /// </summary>
        private IUserBL UserBL { get; set; }

       
        public AccountController(IUserBL bLayer)
        {
            this.UserBL = bLayer;
        }
        
        //
        // GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
            //Casher.LoadStaticCache();
            return View();
        }

        // POST: /Account/Register
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                this.UserBL.CreateUser(model);

                if (this.UserBL.Result.IsValid)
                {
                    TempData["username"] = model.Username;
                    TempData["password"] = model.Password;

                    return RedirectToAction("Login", "Account");
                }
            }

            AddModelErrors();
            return View();
        }

        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login()
        {
            //throw new Exception(); make unhadle exception
            var model = new LoginViewModel()
            {
                Username = TempData["username"] != null ? TempData["username"].ToString() : null,
                Password = TempData["password"] != null ? TempData["password"].ToString() : null,
            };

            return View(model);
        }

        // POST: /Account/Login
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                this.UserBL.LoginUser(model);

                if (this.UserBL.Result.IsValid)
                {
                    return RedirectToAction("Index", "Home");
                }
            }

            AddModelErrors();
            return View();
        }
  
        /// <summary>
        /// Add Errors to ModelState
        /// </summary>
        private void AddModelErrors()
        {
            foreach (var error in this.UserBL.Result.Errors)
            {
                this.ModelState.AddModelError("", error);
            }
        }
    }
}